package com.zaoshui.hudada.scoring;

import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.zaoshui.hudada.model.dto.question.QuestionContentDTO;
import com.zaoshui.hudada.model.entity.App;
import com.zaoshui.hudada.model.entity.Question;
import com.zaoshui.hudada.model.entity.ScoringResult;
import com.zaoshui.hudada.model.entity.UserAnswer;
import com.zaoshui.hudada.service.QuestionService;
import com.zaoshui.hudada.service.ScoringResultService;

import javax.annotation.Resource;
import java.util.List;

@ScoringStrategyConfig(appType = 0,scoringStrategy = 0)
public class CustomScoreScoringStrategy implements ScoringStrategy{

    @Resource
    QuestionService questionService;

    @Resource
    ScoringResultService scoringResultService;

    @Override
    public UserAnswer doScore(List<String> choices, App app) {
        // 1. 根据id获取到题目和评分结果
        Long appId = app.getId();
        Question question = questionService.getOne(
                Wrappers.lambdaQuery(Question.class)
                        .eq(Question::getAppId, appId)
        );
        List<ScoringResult> scoringResultList = scoringResultService.list(
                Wrappers.lambdaQuery(ScoringResult.class)
                        .eq(ScoringResult::getAppId, appId)
                        .orderByDesc(ScoringResult::getResultScoreRange)
        );

        // 2. 根据用户选择的答案与题目答案进行匹配，计算得分
        int userScore = 0;
        List<QuestionContentDTO> questionContentDTOList = JSONUtil.toList(question.getQuestionContent(), QuestionContentDTO.class);
        for (int i = 0; i < choices.size(); i++) {
            for (QuestionContentDTO.Option option : questionContentDTOList.get(i).getOptions()) {
                if(choices.get(i).equals(option.getKey())){
                    userScore += option.getScore();
                }
            }
        }
        // 3. 根据用户的得分，计算出用户的评分结果
        ScoringResult maxScoringResult = scoringResultList.get(0);
        for (ScoringResult scoringResult : scoringResultList) {
            if(userScore >= scoringResult.getResultScoreRange()){
                maxScoringResult = scoringResult;
                break;
            }
        }
        // 4. 构造返回值
        UserAnswer userAnswer = new UserAnswer();
        userAnswer.setAppId(appId);
        userAnswer.setAppType(app.getAppType());
        userAnswer.setScoringStrategy(app.getScoringStrategy());
        userAnswer.setChoices(JSONUtil.toJsonStr(choices));
        userAnswer.setResultId(maxScoringResult.getId());
        userAnswer.setResultName(maxScoringResult.getResultName());
        userAnswer.setResultDesc(maxScoringResult.getResultDesc());
        userAnswer.setResultPicture(maxScoringResult.getResultPicture());
        userAnswer.setResultScore(userScore);
        return userAnswer;
    }
}
